home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1999 May: Tool Chest / Developer CD Series Tool Chest (Apple Computer)(May 1999).iso / Tool Chest / Development Kits / MPW etc / MPW-GM / MPW / Examples / CExamples / TESample.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-12-03  |  49.3 KB  |  1,484 lines  |  [TEXT/MPS ]

  1. /*------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple TextEdit Sample Application
  6. #
  7. #    TESample
  8. #
  9. #    This file: TESample.c    -    C Source
  10. #
  11. #    Copyright © 1989, 1994-95 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89
  18. #                1.03                06/89
  19. #                1.04                03/94
  20. #
  21. #    Components:
  22. #                TESample.c            Feb.  1, 1990
  23. #                TESampleGlue.a        Feb.  1, 1990
  24. #                TESample.r            Feb.  1, 1990
  25. #                TESample.h            Feb.  1, 1990
  26. #                TESample.make        Feb.  1, 1990
  27. #
  28. #    TESample is an example application that demonstrates how 
  29. #    to initialize the commonly used toolbox managers, operate 
  30. #    successfully under MultiFinder, handle desk accessories and 
  31. #    create, grow, and zoom windows. The fundamental TextEdit 
  32. #    toolbox calls and TextEdit autoscroll are demonstrated. It 
  33. #    also shows how to create and maintain scrollbar controls.
  34. #
  35. #    It does not by any means demonstrate all the techniques you 
  36. #    need for a large application. In particular, Sample does not 
  37. #    cover exception handling, multiple windows/documents, 
  38. #    sophisticated memory management, printing, or undo. All of 
  39. #    these are vital parts of a normal full-sized application.
  40. #
  41. #    This application is an example of the form of a Macintosh 
  42. #    application; it is NOT a template. It is NOT intended to be 
  43. #    used as a foundation for the next world-class, best-selling, 
  44. #    600K application. A stick figure drawing of the human body may 
  45. #    be a good example of the form for a painting, but that does not 
  46. #    mean it should be used as the basis for the next Mona Lisa.
  47. #
  48. #    We recommend that you review this program or Sample before 
  49. #    beginning a new application. Sample is a simple app. which doesn’t 
  50. #    use TextEdit or the Control Manager.
  51. #
  52. ------------------------------------------------------------------------------*/
  53.  
  54.  
  55. /* Segmentation strategy:
  56.  
  57.    This program consists of three segments. Main contains most of the code,
  58.    including the MPW libraries, and the main program. Initialize contains
  59.    code that is only used once, during startup, and can be unloaded after the
  60.    program starts. %A5Init is automatically created by the Linker to initialize
  61.    globals for the MPW libraries and is unloaded right away. */
  62.  
  63.  
  64. /* SetPort strategy:
  65.  
  66.    Toolbox routines do not change the current port. In spite of this, in this
  67.    program we use a strategy of calling SetPort whenever we want to draw or
  68.    make calls which depend on the current port. This makes us less vulnerable
  69.    to bugs in other software which might alter the current port (such as the
  70.    bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  71.    Hopefully, this also makes the routines from this program more self-contained,
  72.    since they don't depend on the current port setting. */
  73.  
  74.  
  75. /* Clipboard strategy:
  76.  
  77.    This program does not maintain a private scrap. Whenever a cut, copy, or paste
  78.    occurs, we import/export from the public scrap to TextEdit's scrap right away,
  79.    using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
  80.    the import/export would be in the activate/deactivate event and suspend/resume
  81.    event routines. */
  82.  
  83. #include <Types.h>
  84. #include <TextUtils.h>
  85. #include <Windows.h>
  86. #include <TextEdit.h>
  87. #include <SegLoad.h>
  88. #include <Limits.h>
  89. #include <Scrap.h>
  90. #include <Dialogs.h>
  91. #include <Devices.h>
  92. #include <Fonts.h>
  93. #include <ToolUtils.h>
  94. #include <Traps.h>
  95. #include <Processes.h>
  96. #include <DiskInit.h>
  97.  
  98. #include "TESample.h"        /* bring in all the #defines for TESample */
  99.  
  100. /* A DocumentRecord contains the WindowRecord for one of our document windows,
  101.    as well as the TEHandle for the text we are editing. Other document fields
  102.    can be added to this record as needed. For a similar example, see how the
  103.    Window Manager and Dialog Manager add fields after the GrafPort. */
  104. typedef struct {
  105.     WindowRecord    docWindow;
  106.     TEHandle        docTE;
  107.     ControlHandle    docVScroll;
  108.     ControlHandle    docHScroll;
  109.     ProcPtr            docClik;
  110. } DocumentRecord, *DocumentPeek;
  111.  
  112.  
  113.  
  114. /* The "g" prefix is used to emphasize that a variable is global. */
  115.  
  116. /* GMac is used to hold the result of a SysEnvirons call. This makes
  117.    it convenient for any routine to check the environment. It is
  118.    global information, anyway. */
  119. SysEnvRec    gMac;                /* set up by Initialize */
  120.  
  121. /* The qd global has been removed from the libraries */
  122. QDGlobals qd;
  123.  
  124. /* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  125.    trap is available. If it is false, we know that we must call GetNextEvent. */
  126. Boolean        gHasWaitNextEvent;    /* set up by Initialize */
  127.  
  128. /* GInBackground is maintained by our OSEvent handling routines. Any part of
  129.    the program can check it to find out if it is currently in the background. */
  130. Boolean        gInBackground;        /* maintained by Initialize and DoEvent */
  131.  
  132. /* GNumDocuments is used to keep track of how many open documents there are
  133.    at any time. It is maintained by the routines that open and close documents. */
  134. short        gNumDocuments;        /* maintained by Initialize, DoNew, and DoCloseWindow */
  135.  
  136.  
  137. /* Here are declarations for all of the C routines. In MPW 3.0 we can use
  138.    actual prototypes for parameter type checking. A/UX C does not grok
  139.    prototypes, so eliminate them under A/UX */
  140.     void AlertUser( short error );
  141.     void EventLoop( void );
  142.     void DoEvent( EventRecord *event );
  143.     void AdjustCursor( Point mouse, RgnHandle region );
  144.     void GetGlobalMouse( Point *mouse );
  145.     void DoGrowWindow( WindowPtr window, EventRecord *event );
  146.     void DoZoomWindow( WindowPtr window, short part );
  147.     void ResizedWindow( WindowPtr window );
  148.     void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
  149.     void DoUpdate( WindowPtr window );
  150.     void DoDeactivate( WindowPtr window );
  151.     void DoActivate( WindowPtr window, Boolean becomingActive );
  152.     void DoContentClick( WindowPtr window, EventRecord *event );
  153.     void DoKeyDown( EventRecord *event );
  154.     unsigned long GetSleep( void );
  155.     void CommonAction( ControlHandle control, short *amount );
  156.     pascal void VActionProc( ControlHandle control, short part );
  157.     pascal void HActionProc( ControlHandle control, short part );
  158.     void DoIdle( void );
  159.     void DrawWindow( WindowPtr window );
  160.     void AdjustMenus( void );
  161.     void DoMenuCommand( long menuResult );
  162.     void DoNew( void );
  163.     Boolean DoCloseWindow( WindowPtr window );
  164.     void Terminate( void );
  165.     void Initialize( void );
  166.     void BigBadError( short error );
  167.     void GetTERect( WindowPtr window, Rect *teRect );
  168.     void AdjustViewRect( TEHandle docTE );
  169.     void AdjustTE( WindowPtr window );
  170.     void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE,
  171.                     Boolean canRedraw );
  172.     void AdjustScrollValues( WindowPtr window, Boolean canRedraw );
  173.     void AdjustScrollSizes( WindowPtr window );
  174.     void AdjustScrollbars( WindowPtr window, Boolean needsResize );
  175.     pascal void PascalClikLoop(void);
  176.     pascal ProcPtr GetOldClikLoop(void);
  177.     Boolean IsAppWindow( WindowPtr window );
  178.     Boolean IsDAWindow( WindowPtr window );
  179.     Boolean TrapAvailable( short tNumber, TrapType tType );
  180.  
  181.  
  182. /* Define HiWrd and LoWrd macros for efficiency. */
  183. #define HiWrd(aLong)    (((aLong) >> 16) & 0xFFFF)
  184. #define LoWrd(aLong)    ((aLong) & 0xFFFF)
  185.  
  186. /* Define TopLeft and BotRight macros for convenience. Notice the implicit
  187.    dependency on the ordering of fields within a Rect */
  188. #define TopLeft(aRect)    (* (Point *) &(aRect).top)
  189. #define BotRight(aRect)    (* (Point *) &(aRect).bottom)
  190.  
  191.  
  192. /* This routine is part of the MPW runtime library. This external
  193.    reference to it is done so that we can unload its segment, %A5Init. */
  194.  
  195. extern void _DataInit(void);
  196.  
  197.  
  198. /* A reference to our assembly language routine that gets attached to the clikLoop
  199. field of our TE record. */
  200.  
  201. extern pascal void AsmClikLoop(void);
  202.  
  203. #pragma segment Main
  204. void main(void)
  205. {
  206.     UnloadSeg((Ptr) _DataInit);        /* note that _DataInit must not be in Main! */
  207.     
  208.     /* 1.01 - call to ForceEnvirons removed */
  209.     
  210.     /*    If you have stack requirements that differ from the default,
  211.         then you could use SetApplLimit to increase StackSpace at 
  212.         this point, before calling MaxApplZone. */
  213.     MaxApplZone();                    /* expand the heap so code segments load at the top */
  214.  
  215.     Initialize();                    /* initialize the program */
  216.     UnloadSeg((Ptr) Initialize);    /* note that Initialize must not be in Main! */
  217.  
  218.     EventLoop();                    /* call the main event loop */
  219. }
  220.  
  221.  
  222. /* Get events forever, and handle them by calling DoEvent.
  223.    Also call AdjustCursor each time through the loop. */
  224.  
  225. #pragma segment Main
  226. void EventLoop(void)
  227. {
  228.     RgnHandle    cursorRgn;
  229.     Boolean        gotEvent;
  230.     EventRecord    event;
  231.     Point        mouse;
  232.  
  233.     cursorRgn = NewRgn();            /* we’ll pass WNE an empty region the 1st time thru */
  234.     do {
  235.         /* use WNE if it is available */
  236.         if ( gHasWaitNextEvent ) {
  237.             GetGlobalMouse(&mouse);
  238.             AdjustCursor(mouse, cursorRgn);
  239.             gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
  240.         }
  241.         else {
  242.             SystemTask();
  243.             gotEvent = GetNextEvent(everyEvent, &event);
  244.         }
  245.         if ( gotEvent ) {
  246.             /* make sure we have the right cursor before handling the event */
  247.             AdjustCursor(event.where, cursorRgn);
  248.             DoEvent(&event);
  249.         }
  250.         else
  251.             DoIdle();                /* perform idle tasks when it’s not our event */
  252.         /*    If you are using modeless dialogs that have editText items,
  253.             you will want to call IsDialogEvent to give the caret a chance
  254.             to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  255.             for a non-NIL value before calling IsDialogEvent. */
  256.     } while ( true );    /* loop forever; we quit via ExitToShell */
  257. } /*EventLoop*/
  258.  
  259.  
  260. /* Do the right thing for an event. Determine what kind of event it is, and call
  261.  the appropriate routines. */
  262.  
  263. #pragma segment Main
  264. void DoEvent(EventRecord *event)
  265. {
  266.     short        part, err;
  267.     WindowPtr    window;
  268.     char        key;
  269.     Point        aPoint;
  270.  
  271.     switch ( event->what ) {
  272.         case nullEvent:
  273.             /* we idle for null/mouse moved events ands for events which aren’t
  274.                 ours (see EventLoop) */
  275.             DoIdle();
  276.             break;
  277.         case mouseDown:
  278.             part = FindWindow(event->where, &window);
  279.             switch ( part ) {
  280.                 case inMenuBar:             /* process a mouse menu command (if any) */
  281.                     AdjustMenus();    /* bring ’em up-to-date */
  282.                     DoMenuCommand(MenuSelect(event->where));
  283.                     break;
  284.                 case inSysWindow:           /* let the system handle the mouseDown */
  285.                     SystemClick(event, window);
  286.                     break;
  287.                 case inContent:
  288.                     if ( window != FrontWindow() ) {
  289.                         SelectWindow(window);
  290.                         /*DoEvent(event);*/    /* use this line for "do first click" */
  291.                     } else
  292.                         DoContentClick(window, event);
  293.                     break;
  294.                 case inDrag:                /* pass screenBits.bounds to get all gDevices */
  295.                     DragWindow(window, event->where, &qd.screenBits.bounds);
  296.                     break;
  297.                 case inGoAway:
  298.                     if ( TrackGoAway(window, event->where) )
  299.                         DoCloseWindow(window); /* we don’t care if the user cancelled */
  300.                     break;
  301.                 case inGrow:
  302.                     DoGrowWindow(window, event);
  303.                     break;
  304.                 case inZoomIn:
  305.                 case inZoomOut:
  306.                 if ( TrackBox(window, event->where, part) )
  307.                         DoZoomWindow(window, part);
  308.                     break;
  309.             }
  310.             break;
  311.         case keyDown:
  312.         case autoKey:                       /* check for menukey equivalents */
  313.             key = event->message & charCodeMask;
  314.             if ( event->modifiers & cmdKey ) {    /* Command key down */
  315.                 if ( event->what == keyDown ) {
  316.                     AdjustMenus();            /* enable/disable/check menu items properly */
  317.                     DoMenuCommand(MenuKey(key));
  318.                 }
  319.             } else
  320.                 DoKeyDown(event);
  321.             break;
  322.         case activateEvt:
  323.             DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
  324.             break;
  325.         case updateEvt:
  326.             DoUpdate((WindowPtr) event->message);
  327.             break;
  328.         /*    1.01 - It is not a bad idea to at least call DIBadMount in response
  329.             to a diskEvt, so that the user can format a floppy. */
  330.         case diskEvt:
  331.             if ( HiWord(event->message) != noErr ) {
  332.                 SetPt(&aPoint, kDILeft, kDITop);
  333.                 err = DIBadMount(aPoint, event->message);
  334.             }
  335.             break;
  336.         case kOSEvent:
  337.         /*    1.02 - must BitAND with 0x0FF to get only low byte */
  338.             switch ((event->message >> 24) & 0x0FF) {        /* high byte of message */
  339.                 case kMouseMovedMessage:
  340.                     DoIdle();                    /* mouse-moved is also an idle event */
  341.                     break;
  342.                 case kSuspendResumeMessage:        /* suspend/resume is also an activate/deactivate */
  343.                     gInBackground = (event->message & kResumeMask) == 0;
  344.                     DoActivate(FrontWindow(), !gInBackground);
  345.                     break;
  346.             }
  347.             break;
  348.     }
  349. } /*DoEvent*/
  350.  
  351.  
  352. /*    Change the cursor's shape, depending on its position. This also calculates the region
  353.     where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
  354.     this region, an event is generated. If there is more to the event than just
  355.     “the mouse moved”, we get called before the event is processed to make sure
  356.     the cursor is the right one. In any (ahem) event, this is called again before we
  357.     fall back into WNE. */
  358.  
  359. #pragma segment Main
  360. void AdjustCursor(Point    mouse, RgnHandle region)
  361. {
  362.     WindowPtr    window;
  363.     RgnHandle    arrowRgn;
  364.     RgnHandle    iBeamRgn;
  365.     Rect        iBeamRect;
  366.  
  367.     window = FrontWindow();    /* we only adjust the cursor when we are in front */
  368.     if ( (! gInBackground) && (! IsDAWindow(window)) ) {
  369.         /* calculate regions for different cursor shapes */
  370.         arrowRgn = NewRgn();
  371.         iBeamRgn = NewRgn();
  372.  
  373.         /* start arrowRgn wide open */
  374.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg, kExtremePos, kExtremePos);
  375.  
  376.         /* calculate iBeamRgn */
  377.         if ( IsAppWindow(window) ) {
  378.             iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
  379.             SetPort(window);    /* make a global version of the viewRect */
  380.             LocalToGlobal(&TopLeft(iBeamRect));
  381.             LocalToGlobal(&BotRight(iBeamRect));
  382.             RectRgn(iBeamRgn, &iBeamRect);
  383.             /* we temporarily change the port’s origin to “globalfy” the visRgn */
  384.             SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
  385.             SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
  386.             SetOrigin(0, 0);
  387.         }
  388.  
  389.         /* subtract other regions from arrowRgn */
  390.         DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
  391.  
  392.         /* change the cursor and the region parameter */
  393.         if ( PtInRgn(mouse, iBeamRgn) ) {
  394.             SetCursor(*GetCursor(iBeamCursor));
  395.             CopyRgn(iBeamRgn, region);
  396.         } else {
  397.             SetCursor(&qd.arrow);
  398.             CopyRgn(arrowRgn, region);
  399.         }
  400.  
  401.         DisposeRgn(arrowRgn);
  402.         DisposeRgn(iBeamRgn);
  403.     }
  404. } /*AdjustCursor*/
  405.  
  406.  
  407. /*    Get the global coordinates of the mouse. When you call OSEventAvail
  408.     it will return either a pending event or a null event. In either case,
  409.     the where field of the event record will contain the current position
  410.     of the mouse in global coordinates and the modifiers field will reflect
  411.     the current state of the modifiers. Another way to get the global
  412.     coordinates is to call GetMouse and LocalToGlobal, but that requires
  413.     being sure that thePort is set to a valid port. */
  414.  
  415. #pragma segment Main
  416. void GetGlobalMouse(Point *mouse)
  417. {
  418.     EventRecord    event;
  419.     
  420.     OSEventAvail(kNoEvents, &event);    /* we aren't interested in any events */
  421.     *mouse = event.where;                /* just the mouse position */
  422. } /*GetGlobalMouse*/
  423.  
  424.  
  425. /*    Called when a mouseDown occurs in the grow box of an active window. In
  426.     order to eliminate any 'flicker', we want to invalidate only what is
  427.     necessary. Since ResizedWindow invalidates the whole portRect, we save
  428.     the old TE viewRect, intersect it with the new TE viewRect, and
  429.     remove the result from the update region. However, we must make sure
  430.     that any old update region that might have been around gets put back. */
  431.  
  432. #pragma segment Main
  433. void DoGrowWindow(WindowPtr    window, EventRecord    *event)
  434. {
  435.     long        growResult;
  436.     Rect        tempRect;
  437.     RgnHandle    tempRgn;
  438.     DocumentPeek doc;
  439.     
  440.     tempRect = qd.screenBits.bounds;                    /* set up limiting values */
  441.     tempRect.left = kMinDocDim;
  442.     tempRect.top = kMinDocDim;
  443.     growResult = GrowWindow(window, event->where, &tempRect);
  444.     /* see if it really changed size */
  445.     if ( growResult != 0 ) {
  446.         doc = (DocumentPeek) window;
  447.         tempRect = (*doc->docTE)->viewRect;                /* save old text box */
  448.         tempRgn = NewRgn();
  449.         GetLocalUpdateRgn(window, tempRgn);                /* get localized update region */
  450.         SizeWindow(window, LoWrd(growResult), HiWrd(growResult), true);
  451.         ResizedWindow(window);
  452.         /* calculate & validate the region that hasn’t changed so it won’t get redrawn */
  453.         SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
  454.         ValidRect(&tempRect);                            /* take it out of update */
  455.         InvalRgn(tempRgn);                                /* put back any prior update */
  456.         DisposeRgn(tempRgn);
  457.     }
  458. } /* DoGrowWindow */
  459.  
  460.  
  461. /*     Called when a mouseClick occurs in the zoom box of an active window.
  462.     Everything has to get re-drawn here, so we don't mind that
  463.     ResizedWindow invalidates the whole portRect. */
  464.  
  465. #pragma segment Main
  466. void DoZoomWindow(WindowPtr    window, short part)
  467. {
  468.     EraseRect(&window->portRect);
  469.     ZoomWindow(window, part, window == FrontWindow());
  470.     ResizedWindow(window);
  471. } /*  DoZoomWindow */
  472.  
  473.  
  474. /* Called when the window has been resized to fix up the controls and content. */
  475. #pragma segment Main
  476. void ResizedWindow(WindowPtr    window)
  477. {
  478.     AdjustScrollbars(window, true);
  479.     AdjustTE(window);
  480.     InvalRect(&window->portRect);
  481. } /* ResizedWindow */
  482.  
  483.  
  484. /* Returns the update region in local coordinates */
  485. #pragma segment Main
  486. void GetLocalUpdateRgn(WindowPtr window, RgnHandle localRgn)
  487. {
  488.     CopyRgn(((WindowPeek) window)->updateRgn, localRgn);    /* save old update region */
  489.     OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
  490. } /* GetLocalUpdateRgn */
  491.  
  492.  
  493. /*    This is called when an update event is received for a window.
  494.     It calls DrawWindow to draw the contents of an application window.
  495.     As an efficiency measure that does not have to be followed, it
  496.     calls the drawing routine only if the visRgn is non-empty. This
  497.     will handle situations where calculations for drawing or drawing
  498.     itself is very time-consuming. */
  499.  
  500. #pragma segment Main
  501. void DoUpdate(WindowPtr    window)
  502. {
  503.     if ( IsAppWindow(window) ) {
  504.         BeginUpdate(window);                /* this sets up the visRgn */
  505.         if ( ! EmptyRgn(window->visRgn) )    /* draw if updating needs to be done */
  506.             DrawWindow(window);
  507.         EndUpdate(window);
  508.     }
  509. } /*DoUpdate*/
  510.  
  511.  
  512. /*    This is called when a window is activated or deactivated.
  513.     It calls TextEdit to deal with the selection. */
  514.  
  515. #pragma segment Main
  516. void DoActivate(WindowPtr window, Boolean becomingActive)
  517. {
  518.     RgnHandle    tempRgn, clipRgn;
  519.     Rect        growRect;
  520.     DocumentPeek doc;
  521.     
  522.     if ( IsAppWindow(window) ) {
  523.         doc = (DocumentPeek) window;
  524.         if ( becomingActive ) {
  525.             /*    since we don’t want TEActivate to draw a selection in an area where
  526.                 we’re going to erase and redraw, we’ll clip out the update region
  527.                 before calling it. */
  528.             tempRgn = NewRgn();
  529.             clipRgn = NewRgn();
  530.             GetLocalUpdateRgn(window, tempRgn);            /* get localized update region */
  531.             GetClip(clipRgn);
  532.             DiffRgn(clipRgn, tempRgn, tempRgn);            /* subtract updateRgn from clipRgn */
  533.             SetClip(tempRgn);
  534.             TEActivate(doc->docTE);
  535.             SetClip(clipRgn);                            /* restore the full-blown clipRgn */
  536.             DisposeRgn(tempRgn);
  537.             DisposeRgn(clipRgn);
  538.             
  539.             /* the controls must be redrawn on activation: */
  540.             (*doc->docVScroll)->contrlVis = kControlVisible;
  541.             (*doc->docHScroll)->contrlVis = kControlVisible;
  542.             InvalRect(&(*doc->docVScroll)->contrlRect);
  543.             InvalRect(&(*doc->docHScroll)->contrlRect);
  544.             /* the growbox needs to be redrawn on activation: */
  545.             growRect = window->portRect;
  546.             /* adjust for the scrollbars */
  547.             growRect.top = growRect.bottom - kScrollbarAdjust;
  548.             growRect.left = growRect.right - kScrollbarAdjust;
  549.             InvalRect(&growRect);
  550.         }
  551.         else {        
  552.             TEDeactivate(doc->docTE);
  553.             /* the controls must be hidden on deactivation: */
  554.             HideControl(doc->docVScroll);
  555.             HideControl(doc->docHScroll);
  556.             /* the growbox should be changed immediately on deactivation: */
  557.             DrawGrowIcon(window);
  558.         }
  559.     }
  560. } /*DoActivate*/
  561.  
  562.  
  563. /*    This is called when a mouseDown occurs in the content of a window. */
  564.  
  565. #pragma segment Main
  566. void DoContentClick(WindowPtr window, EventRecord *event)
  567. {
  568.     Point        mouse;
  569.     ControlHandle control;
  570.     short        part, value;
  571.     Boolean        shiftDown;
  572.     DocumentPeek doc;
  573.     Rect        teRect;
  574.  
  575.     if ( IsAppWindow(window) ) {
  576.         SetPort(window);
  577.         mouse = event->where;                            /* get the click position */
  578.         GlobalToLocal(&mouse);
  579.         doc = (DocumentPeek) window;
  580.         /* see if we are in the viewRect. if so, we won’t check the controls */
  581.         GetTERect(window, &teRect);
  582.         if ( PtInRect(mouse, &teRect) ) {
  583.             /* see if we need to extend the selection */
  584.             shiftDown = (event->modifiers & shiftKey) != 0;    /* extend if Shift is down */
  585.             TEClick(mouse, shiftDown, doc->docTE);
  586.         } else {
  587.             part = FindControl(mouse, window, &control);
  588.             switch ( part ) {
  589.                 case 0:                            /* do nothing for viewRect case */
  590.                     break;
  591.                 case kControlIndicatorPart:
  592.                     value = GetControlValue(control);
  593.                     part = TrackControl(control, mouse, nil);
  594.                     if ( part != 0 ) {
  595.                         value -= GetControlValue(control);
  596.                         /* value now has CHANGE in value; if value changed, scroll */
  597.                         if ( value != 0 )
  598.                             if ( control == doc->docVScroll )
  599.                                 TEScroll(0, value * (*doc->docTE)->lineHeight, doc->docTE);
  600.                             else
  601.                                 TEScroll(value, 0, doc->docTE);
  602.                     }
  603.                     break;
  604.                 default:                        /* they clicked in an arrow, so track & scroll */
  605.                     if ( control == doc->docVScroll )
  606.                         value = TrackControl(control, mouse, (ControlActionUPP) VActionProc);
  607.                     else
  608.                         value = TrackControl(control, mouse, (ControlActionUPP) HActionProc);
  609.                     break;
  610.             }
  611.         }
  612.     }
  613. } /*DoContentClick*/
  614.  
  615.  
  616. /* This is called for any keyDown or autoKey events, except when the
  617.  Command key is held down. It looks at the frontmost window to decide what
  618.  to do with the key typed. */
  619.  
  620. #pragma segment Main
  621. void DoKeyDown(EventRecord *event)
  622. {
  623.     WindowPtr    window;
  624.     char        key;
  625.     TEHandle    te;
  626.  
  627.     window = FrontWindow();
  628.     if ( IsAppWindow(window) ) {
  629.         te = ((DocumentPeek) window)->docTE;
  630.         key = event->message & charCodeMask;
  631.         /* we have a char. for our window; see if we are still below TextEdit’s
  632.             limit for the number of characters (but deletes are always rad) */
  633.         if ( key == kDelChar ||
  634.                 (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 <
  635.                 kMaxTELength ) {
  636.             TEKey(key, te);
  637.             AdjustScrollbars(window, false);
  638.             AdjustTE(window);
  639.         } else
  640.             AlertUser(eExceedChar);
  641.     }
  642. } /*DoKeyDown*/
  643.  
  644.  
  645. /*    Calculate a sleep value for WaitNextEvent. This takes into account the things
  646.     that DoIdle does with idle time. */
  647.  
  648. #pragma segment Main
  649. unsigned long GetSleep(void)
  650. {
  651.     long        sleep;
  652.     WindowPtr    window;
  653.     TEHandle    te;
  654.  
  655.     sleep = LONG_MAX;                        /* default value for sleep */
  656.     if ( !gInBackground ) {
  657.         window = FrontWindow();            /* and the front window is ours... */
  658.         if ( IsAppWindow(window) ) {
  659.             te = ((DocumentPeek) (window))->docTE;    /* and the selection is an insertion point... */
  660.             if ( (*te)->selStart == (*te)->selEnd )
  661.                 sleep = GetCaretTime();        /* blink time for the insertion point */
  662.         }
  663.     }
  664.     return sleep;
  665. } /*GetSleep*/
  666.  
  667.  
  668. /*    Common algorithm for pinning the value of a control. It returns the actual amount
  669.     the value of the control changed. Note the pinning is done for the sake of returning
  670.     the amount the control value changed. */
  671.  
  672. #pragma segment Main
  673. void CommonAction(ControlHandle control, short *amount)
  674. {
  675.     short        value, max;
  676.     
  677.     value = GetControlValue(control);    /* get current value */
  678.     max = GetControlMaximum(control);    /* and maximum value */
  679.     *amount = value - *amount;
  680.     if ( *amount < 0 )
  681.         *amount = 0;
  682.     else if ( *amount > max )
  683.         *amount = max;
  684.     SetControlValue(control, *amount);
  685.     *amount = value - *amount;        /* calculate the real change */
  686. } /* CommonAction */
  687.  
  688.  
  689. /* Determines how much to change the value of the vertical scrollbar by and how
  690.     much to scroll the TE record. */
  691.  
  692. #pragma segment Main
  693. pascal void VActionProc(ControlHandle control, short part)
  694. {
  695.     short        amount;
  696.     WindowPtr    window;
  697.     TEPtr        te;
  698.     
  699.     if ( part != 0 ) {                /* if it was actually in the control */
  700.         window = (*control)->contrlOwner;
  701.         te = *((DocumentPeek) window)->docTE;
  702.         switch ( part ) {
  703.             case kControlUpButtonPart:
  704.             case kControlDownButtonPart:        /* one line */
  705.                 amount = 1;
  706.                 break;
  707.             case kControlPageUpPart:            /* one page */
  708.             case kControlPageDownPart:
  709.                 amount = (te->viewRect.bottom - te->viewRect.top) / te->lineHeight;
  710.                 break;
  711.         }
  712.         if ( (part == kControlDownButtonPart) || (part == kControlPageDownPart) )
  713.             amount = -amount;        /* reverse direction for a downer */
  714.         CommonAction(control, &amount);
  715.         if ( amount != 0 )
  716.             TEScroll(0, amount * te->lineHeight, ((DocumentPeek) window)->docTE);
  717.     }
  718. } /* VActionProc */
  719.  
  720.  
  721. /* Determines how much to change the value of the horizontal scrollbar by and how
  722. much to scroll the TE record. */
  723.  
  724. #pragma segment Main
  725. pascal void HActionProc(ControlHandle control, short part)
  726. {
  727.     short        amount;
  728.     WindowPtr    window;
  729.     TEPtr        te;
  730.     
  731.     if ( part != 0 ) {
  732.         window = (*control)->contrlOwner;
  733.         te = *((DocumentPeek) window)->docTE;
  734.         switch ( part ) {
  735.             case kControlUpButtonPart:
  736.             case kControlDownButtonPart:        /* a few pixels */
  737.                 amount = kButtonScroll;
  738.                 break;
  739.             case kControlPageUpPart:            /* a page */
  740.             case kControlPageDownPart:
  741.                 amount = te->viewRect.right - te->viewRect.left;
  742.                 break;
  743.         }
  744.         if ( (part == kControlDownButtonPart) || (part == kControlPageDownPart) )
  745.             amount = -amount;        /* reverse direction */
  746.         CommonAction(control, &amount);
  747.         if ( amount != 0 )
  748.             TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
  749.     }
  750. } /* VActionProc */
  751.  
  752.  
  753. /* This is called whenever we get a null event et al.
  754.  It takes care of necessary periodic actions. For this program, it calls TEIdle. */
  755.  
  756. #pragma segment Main
  757. void DoIdle(void)
  758. {
  759.     WindowPtr    window;
  760.  
  761.     window = FrontWindow();
  762.     if ( IsAppWindow(window) )
  763.         TEIdle(((DocumentPeek) window)->docTE);
  764. } /*DoIdle*/
  765.  
  766.  
  767. /* Draw the contents of an application window. */
  768.  
  769. #pragma segment Main
  770. void DrawWindow(WindowPtr window)
  771. {
  772.     SetPort(window);
  773.     EraseRect(&window->portRect);
  774.     DrawControls(window);
  775.     DrawGrowIcon(window);
  776.     TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
  777. } /*DrawWindow*/
  778.  
  779.  
  780. /*    Enable and disable menus based on the current state.
  781.     The user can only select enabled menu items. We set up all the menu items
  782.     before calling MenuSelect or MenuKey, since these are the only times that
  783.     a menu item can be selected. Note that MenuSelect is also the only time
  784.     the user will see menu items. This approach to deciding what enable/
  785.     disable state a menu item has the advantage of concentrating all
  786.     the decision-making in one routine, as opposed to being spread throughout
  787.     the application. Other application designs may take a different approach
  788.     that may or may not be as valid. */
  789.  
  790. #pragma segment Main
  791. void AdjustMenus(void)
  792. {
  793.     WindowPtr    window;
  794.     MenuHandle    menu;
  795.     long        offset;
  796.     Boolean        undo;
  797.     Boolean        cutCopyClear;
  798.     Boolean        paste;
  799.     TEHandle    te;
  800.  
  801.     window = FrontWindow();
  802.  
  803.     menu = GetMenuHandle(mFile);
  804.     if ( gNumDocuments < kMaxOpenDocuments )
  805.         EnableItem(menu, iNew);        /* New is enabled when we can open more documents */
  806.     else
  807.         DisableItem(menu, iNew);
  808.     if ( window != nil )            /* Close is enabled when there is a window to close */
  809.         EnableItem(menu, iClose);
  810.     else
  811.         DisableItem(menu, iClose);
  812.  
  813.     menu = GetMenuHandle(mEdit);
  814.     undo = false;
  815.     cutCopyClear = false;
  816.     paste = false;
  817.     if ( IsDAWindow(window) ) {
  818.         undo = true;                /* all editing is enabled for DA windows */
  819.         cutCopyClear = true;
  820.         paste = true;
  821.     } else if ( IsAppWindow(window) ) {
  822.         te = ((DocumentPeek) window)->docTE;
  823.         if ( (*te)->selStart < (*te)->selEnd )
  824.             cutCopyClear = true;
  825.             /* Cut, Copy, and Clear is enabled for app. windows with selections */
  826.         if ( GetScrap(nil, 'TEXT', &offset)  > 0)
  827.             paste = true;            /* if there’s any text in the clipboard, paste is enabled */
  828.     }
  829.     if ( undo )
  830.         EnableItem(menu, iUndo);
  831.     else
  832.         DisableItem(menu, iUndo);
  833.     if ( cutCopyClear ) {
  834.         EnableItem(menu, iCut);
  835.         EnableItem(menu, iCopy);
  836.         EnableItem(menu, iClear);
  837.     } else {
  838.         DisableItem(menu, iCut);
  839.         DisableItem(menu, iCopy);
  840.         DisableItem(menu, iClear);
  841.     }
  842.     if ( paste )
  843.         EnableItem(menu, iPaste);
  844.     else
  845.         DisableItem(menu, iPaste);
  846. } /*AdjustMenus*/
  847.  
  848.  
  849. /*    This is called when an item is chosen from the menu bar (after calling
  850.     MenuSelect or MenuKey). It does the right thing for each command. */
  851.  
  852. #pragma segment Main
  853. void DoMenuCommand(long    menuResult)
  854. {
  855.     short        menuID, menuItem;
  856.     short        itemHit, daRefNum;
  857.     Str255        daName;
  858.     OSErr        saveErr;
  859.     TEHandle    te;
  860.     WindowPtr    window;
  861.     Handle        aHandle;
  862.     long        oldSize, newSize;
  863.     long        total, contig;
  864.  
  865.     window = FrontWindow();
  866.     menuID = HiWord(menuResult);    /* use macros for efficiency to... */
  867.     menuItem = LoWord(menuResult);    /* get menu item number and menu number */
  868.     switch ( menuID ) {
  869.         case mApple:
  870.             switch ( menuItem ) {
  871.                 case iAbout:        /* bring up alert for About */
  872.                     itemHit = Alert(rAboutAlert, nil);
  873.                     break;
  874.                 default:            /* all non-About items in this menu are DAs et al */
  875.                     /* type Str255 is an array in MPW 3 */
  876.                     GetMenuItemText(GetMenuHandle(mApple), menuItem, daName);
  877.                     daRefNum = OpenDeskAcc(daName);
  878.                     break;
  879.             }
  880.             break;
  881.         case mFile:
  882.             switch ( menuItem ) {
  883.                 case iNew:
  884.                     DoNew();
  885.                     break;
  886.                 case iClose:
  887.                     DoCloseWindow(FrontWindow());            /* ignore the result */
  888.                     break;
  889.                 case iQuit:
  890.                     Terminate();
  891.                     break;
  892.             }
  893.             break;
  894.         case mEdit:                    /* call SystemEdit for DA editing & MultiFinder */
  895.             if ( !SystemEdit(menuItem-1) ) {
  896.                 te = ((DocumentPeek) FrontWindow())->docTE;
  897.                 switch ( menuItem ) {
  898.                     case iCut:
  899.                         if ( ZeroScrap() == noErr ) {
  900.                             PurgeSpace(&total, &contig);
  901.                             if ((*te)->selEnd - (*te)->selStart + kTESlop > contig)
  902.                                 AlertUser(eNoSpaceCut);
  903.                             else 
  904.                                 {
  905.                                 TECut(te);
  906.                                 if ( TEToScrap() != noErr ) {
  907.                                     AlertUser(eNoCut);
  908.                                     ZeroScrap();
  909.                                 }
  910.                             }
  911.                         }
  912.                         break;
  913.                     case iCopy:
  914.                         if ( ZeroScrap() == noErr ) {
  915.                             TECopy(te);    /* after copying, export the TE scrap */
  916.                             if ( TEToScrap() != noErr ) {
  917.                                 AlertUser(eNoCopy);
  918.                                 ZeroScrap();
  919.                             }
  920.                         }
  921.                         break;
  922.                     case iPaste:    /* import the TE scrap before pasting */
  923.                         if ( TEFromScrap() == noErr ) {
  924.                             if ( TEGetScrapLength() + ((*te)->teLength -
  925.                                 ((*te)->selEnd - (*te)->selStart)) > kMaxTELength )
  926.                                 AlertUser(eExceedPaste);
  927.                             else {
  928.                                 aHandle = (Handle) TEGetText(te);
  929.                                 oldSize = GetHandleSize(aHandle);
  930.                                 newSize = oldSize + TEGetScrapLength() + kTESlop;
  931.                                 SetHandleSize(aHandle, newSize);
  932.                                 saveErr = MemError();
  933.                                 SetHandleSize(aHandle, oldSize);
  934.                                 if (saveErr != noErr)
  935.                                     AlertUser(eNoSpacePaste);
  936.                                 else
  937.                                     TEPaste(te);
  938.                             }
  939.                         }
  940.                         else
  941.                             AlertUser(eNoPaste);
  942.                         break;
  943.                     case iClear:
  944.                         TEDelete(te);
  945.                         break;
  946.                 }
  947.             AdjustScrollbars(window, false);
  948.             AdjustTE(window);
  949.             }
  950.             break;
  951.     }
  952.     HiliteMenu(0);                    /* unhighlight what MenuSelect (or MenuKey) hilited */
  953. } /*DoMenuCommand*/
  954.  
  955.  
  956. /* Create a new document and window. */
  957.  
  958. #pragma segment Main
  959. void DoNew(void)
  960. {
  961.     Boolean        good;
  962.     Ptr            storage;
  963.     WindowPtr    window;
  964.     Rect        destRect, viewRect;
  965.     DocumentPeek doc;
  966.  
  967.     storage = NewPtr(sizeof(DocumentRecord));
  968.     if ( storage != nil ) {
  969.         window = GetNewWindow(rDocWindow, storage, (WindowPtr) -1);
  970.         if ( window != nil ) {
  971.             gNumDocuments += 1;            /* this will be decremented when we call DoCloseWindow */
  972.             good = false;
  973.             SetPort(window);
  974.             doc =  (DocumentPeek) window;
  975.             GetTERect(window, &viewRect);
  976.             destRect = viewRect;
  977.             destRect.right = destRect.left + kMaxDocWidth;
  978.             doc->docTE = TENew(&destRect, &viewRect);
  979.             good = doc->docTE != nil;    /* if TENew succeeded, we have a good document */
  980.             if ( good ) {                /* 1.02 - good document? — proceed */
  981.                 AdjustViewRect(doc->docTE);
  982.                 TEAutoView(true, doc->docTE);
  983.                 doc->docClik = (ProcPtr) (*doc->docTE)->clickLoop;
  984.                 (*doc->docTE)->clickLoop = (TEClickLoopUPP) AsmClikLoop;
  985.             }
  986.             
  987.             if ( good ) {                /* good document? — get scrollbars */
  988.                 doc->docVScroll = GetNewControl(rVScroll, window);
  989.                 good = (doc->docVScroll != nil);
  990.             }
  991.             if ( good) {
  992.                 doc->docHScroll = GetNewControl(rHScroll, window);
  993.                 good = (doc->docHScroll != nil);
  994.             }
  995.             
  996.             if ( good ) {                /* good? — adjust & draw the controls, draw the window */
  997.                 /* false to AdjustScrollValues means musn’t redraw; technically, of course,
  998.                 the window is hidden so it wouldn’t matter whether we called ShowControl or not. */
  999.                 AdjustScrollValues(window, false);
  1000.                 ShowWindow(window);
  1001.             } else {
  1002.                 DoCloseWindow(window);    /* otherwise regret we ever created it... */
  1003.                 AlertUser(eNoWindow);            /* and tell user */
  1004.             }
  1005.         } else
  1006.             DisposePtr(storage);            /* get rid of the storage if it is never used */
  1007.     }
  1008. } /*DoNew*/
  1009.  
  1010.  
  1011. /* Close a window. This handles desk accessory and application windows. */
  1012.  
  1013. /*    1.01 - At this point, if there was a document associated with a
  1014.     window, you could do any document saving processing if it is 'dirty'.
  1015.     DoCloseWindow would return true if the window actually closed, i.e.,
  1016.     the user didn’t cancel from a save dialog. This result is handy when
  1017.     the user quits an application, but then cancels the save of a document
  1018.     associated with a window. */
  1019.  
  1020. #pragma segment Main
  1021. Boolean DoCloseWindow(WindowPtr    window)
  1022. {
  1023.     TEHandle    te;
  1024.  
  1025.     if ( IsDAWindow(window) )
  1026.         CloseDeskAcc(((WindowPeek) window)->windowKind);
  1027.     else if ( IsAppWindow(window) ) {
  1028.         te = ((DocumentPeek) window)->docTE;
  1029.         if ( te != nil )
  1030.             TEDispose(te);            /* dispose the TEHandle if we got far enough to make one */
  1031.         /*    1.01 - We used to call DisposeWindow, but that was technically
  1032.             incorrect, even though we allocated storage for the window on
  1033.             the heap. We should instead call CloseWindow to have the structures
  1034.             taken care of and then dispose of the storage ourselves. */
  1035.         CloseWindow(window);
  1036.         DisposePtr((Ptr) window);
  1037.         gNumDocuments -= 1;
  1038.     }
  1039.     return true;
  1040. } /*DoCloseWindow*/
  1041.  
  1042.  
  1043. /**************************************************************************************
  1044. *** 1.01 DoCloseBehind(window) was removed ***
  1045.  
  1046.     1.01 - DoCloseBehind was a good idea for closing windows when quitting
  1047.     and not having to worry about updating the windows, but it suffered
  1048.     from a fatal flaw. If a desk accessory owned two windows, it would
  1049.     close both those windows when CloseDeskAcc was called. When DoCloseBehind
  1050.     got around to calling DoCloseWindow for that other window that was already
  1051.     closed, things would go very poorly. Another option would be to have a
  1052.     procedure, GetRearWindow, that would go through the window list and return
  1053.     the last window. Instead, we decided to present the standard approach
  1054.     of getting and closing FrontWindow until FrontWindow returns NIL. This
  1055.     has a potential benefit in that the window whose document needs to be saved
  1056.     may be visible since it is the front window, therefore decreasing the
  1057.     chance of user confusion. For aesthetic reasons, the windows in the
  1058.     application should be checked for updates periodically and have the
  1059.     updates serviced.
  1060. **************************************************************************************/
  1061.  
  1062.  
  1063. /* Clean up the application and exit. We close all of the windows so that
  1064.  they can update their documents, if any. */
  1065.  
  1066. /*    1.01 - If we find out that a cancel has occurred, we won't exit to the
  1067.     shell, but will return instead. */
  1068.  
  1069. #pragma segment Main
  1070. void Terminate(void)
  1071. {
  1072.     WindowPtr    aWindow;
  1073.     Boolean        closed;
  1074.     
  1075.     closed = true;
  1076.     do {
  1077.         aWindow = FrontWindow();                /* get the current front window */
  1078.         if (aWindow != nil)
  1079.             closed = DoCloseWindow(aWindow);    /* close this window */    
  1080.     }
  1081.     while (closed && (aWindow != nil));
  1082.     if (closed)
  1083.         ExitToShell();                            /* exit if no cancellation */
  1084. } /*Terminate*/
  1085.  
  1086.  
  1087. /*    Set up the whole world, including global variables, Toolbox managers,
  1088.     menus, and a single blank document. */
  1089.  
  1090. /*    1.01 - The code that used to be part of ForceEnvirons has been moved into
  1091.     this module. If an error is detected, instead of merely doing an ExitToShell,
  1092.     which leaves the user without much to go on, we call AlertUser, which puts
  1093.     up a simple alert that just says an error occurred and then calls ExitToShell.
  1094.     Since there is no other cleanup needed at this point if an error is detected,
  1095.     this form of error- handling is acceptable. If more sophisticated error recovery
  1096.     is needed, an exception mechanism, such as is provided by Signals, can be used. */
  1097.  
  1098. #pragma segment Initialize
  1099. void Initialize(void)
  1100. {
  1101.     Handle    menuBar;
  1102.     long    total, contig;
  1103.     EventRecord event;
  1104.     short    count;
  1105.  
  1106.     gInBackground = false;
  1107.  
  1108.     InitGraf((Ptr) &qd.thePort);
  1109.     InitFonts();
  1110.     InitWindows();
  1111.     InitMenus();
  1112.     TEInit();
  1113.     InitDialogs(nil);
  1114.     InitCursor();
  1115.  
  1116.     /*    Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  1117.          if you are using it. */
  1118.     /*    NOTE -- It is no longer necessary, and actually unhealthy, to check
  1119.         PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  1120.         of checking for port availability themselves. */
  1121.     
  1122.     /*    This next bit of code is necessary to allow the default button of our
  1123.         alert be outlined.
  1124.         1.02 - Changed to call EventAvail so that we don't lose some important
  1125.         events. */
  1126.      
  1127.     for (count = 1; count <= 3; count++)
  1128.         EventAvail(everyEvent, &event);
  1129.     
  1130.     /*    Ignore the error returned from SysEnvirons; even if an error occurred,
  1131.         the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  1132.         call to SysEnvirons by calling it after initializing AppleTalk. */
  1133.      
  1134.     SysEnvirons(kSysEnvironsVersion, &gMac);
  1135.     
  1136.     /* Make sure that the machine has at least 128K ROMs. If it doesn't, exit. */
  1137.     
  1138.     if (gMac.machineType < 0) BigBadError(eWrongMachine);
  1139.     
  1140.     /*    1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  1141.         in TrapAvailable if a tool trap value is out of range. */
  1142.         
  1143.     gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
  1144.  
  1145.     /*    1.01 - We used to make a check for memory at this point by examining ApplLimit,
  1146.         ApplicZone, and StackSpace and comparing that to the minimum size we told
  1147.         MultiFinder we needed. This did not work well because it assumed too much about
  1148.         the relationship between what we asked MultiFinder for and what we would actually
  1149.         get back, as well as how to measure it. Instead, we will use an alternate
  1150.         method comprised of two steps. */
  1151.      
  1152.     /*    It is better to first check the size of the application heap against a value
  1153.         that you have determined is the smallest heap the application can reasonably
  1154.         work in. This number should be derived by examining the size of the heap that
  1155.         is actually provided by MultiFinder when the minimum size requested is used.
  1156.         The derivation of the minimum size requested from MultiFinder is described
  1157.         in Sample.h. The check should be made because the preferred size can end up
  1158.         being set smaller than the minimum size by the user. This extra check acts to
  1159.         insure that your application is starting from a solid memory foundation. */
  1160.      
  1161.     if ((long) GetApplLimit() - (long) ApplicationZone() < kMinHeap) BigBadError(eSmallSize);
  1162.     
  1163.     /*    Next, make sure that enough memory is free for your application to run. It
  1164.         is possible for a situation to arise where the heap may have been of required
  1165.         size, but a large scrap was loaded which left too little memory. To check for
  1166.         this, call PurgeSpace and compare the result with a value that you have determined
  1167.         is the minimum amount of free memory your application needs at initialization.
  1168.         This number can be derived several different ways. One way that is fairly
  1169.         straightforward is to run the application in the minimum size configuration
  1170.         as described previously. Call PurgeSpace at initialization and examine the value
  1171.         returned. However, you should make sure that this result is not being modified
  1172.         by the scrap's presence. You can do that by calling ZeroScrap before calling
  1173.         PurgeSpace. Make sure to remove that call before shipping, though. */
  1174.     
  1175.     /* ZeroScrap(); */
  1176.  
  1177.     PurgeSpace(&total, &contig);
  1178.     if (total < kMinSpace)
  1179.         if (UnloadScrap() != noErr)
  1180.             BigBadError(eNoMemory);
  1181.         else {
  1182.             PurgeSpace(&total, &contig);
  1183.             if (total < kMinSpace)
  1184.                 BigBadError(eNoMemory);
  1185.         }
  1186.  
  1187.     /*    The extra benefit to waiting until after the Toolbox Managers have been initialized
  1188.         to check memory is that we can now give the user an alert to tell him/her what
  1189.         happened. Although it is possible that the memory situation could be worsened by
  1190.         displaying an alert, MultiFinder would gracefully exit the application with
  1191.         an informative alert if memory became critical. Here we are acting more
  1192.         in a preventative manner to avoid future disaster from low-memory problems. */
  1193.  
  1194.     menuBar = GetNewMBar(rMenuBar);            /* read menus into menu bar */
  1195.     if ( menuBar == nil )
  1196.                 BigBadError(eNoMemory);
  1197.     SetMenuBar(menuBar);                    /* install menus */
  1198.     DisposeHandle(menuBar);
  1199.     AppendResMenu(GetMenuHandle(mApple), 'DRVR');    /* add DA names to Apple menu */
  1200.     DrawMenuBar();
  1201.  
  1202.     gNumDocuments = 0;
  1203.  
  1204.     /* do other initialization here */
  1205.  
  1206.     DoNew();                                /* create a single empty document */
  1207. } /*Initialize*/
  1208.  
  1209.  
  1210. /* Used whenever a, like, fully fatal error happens */
  1211. #pragma segment Initialize
  1212. void BigBadError(short error)
  1213. {
  1214.     AlertUser(error);
  1215.     ExitToShell();
  1216. }
  1217.  
  1218.  
  1219. /* Return a rectangle that is inset from the portRect by the size of
  1220.     the scrollbars and a little extra margin. */
  1221.  
  1222. #pragma segment Main
  1223. void GetTERect(WindowPtr window, Rect *teRect)
  1224. {
  1225.     *teRect = window->portRect;
  1226.     InsetRect(teRect, kTextMargin, kTextMargin);    /* adjust for margin */
  1227.     teRect->bottom = teRect->bottom - 15;        /* and for the scrollbars */
  1228.     teRect->right = teRect->right - 15;
  1229. } /*GetTERect*/
  1230.  
  1231.  
  1232. /* Update the TERec's view rect so that it is the greatest multiple of
  1233.     the lineHeight that still fits in the old viewRect. */
  1234.  
  1235. #pragma segment Main
  1236. void AdjustViewRect(TEHandle docTE)
  1237. {
  1238.     TEPtr        te;
  1239.     
  1240.     te = *docTE;
  1241.     te->viewRect.bottom = (((te->viewRect.bottom - te->viewRect.top) / te->lineHeight)
  1242.                             * te->lineHeight) + te->viewRect.top;
  1243. } /*AdjustViewRect*/
  1244.  
  1245.  
  1246. /* Scroll the TERec around to match up to the potentially updated scrollbar
  1247.     values. This is really useful when the window has been resized such that the
  1248.     scrollbars became inactive but the TERec was already scrolled. */
  1249.  
  1250. #pragma segment Main
  1251. void AdjustTE(WindowPtr    window)
  1252. {
  1253.     TEPtr        te;
  1254.     
  1255.     te = *((DocumentPeek)window)->docTE;
  1256.     TEScroll((te->viewRect.left - te->destRect.left) -
  1257.             GetControlValue(((DocumentPeek)window)->docHScroll),
  1258.             (te->viewRect.top - te->destRect.top) -
  1259.                 (GetControlValue(((DocumentPeek)window)->docVScroll) *
  1260.                 te->lineHeight),
  1261.             ((DocumentPeek)window)->docTE);
  1262. } /*AdjustTE*/
  1263.  
  1264.  
  1265. /* Calculate the new control maximum value and current value, whether it is the horizontal or
  1266.     vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
  1267.     vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
  1268.     width to the width of the viewRect. The current values are set by comparing the offset between
  1269.     the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
  1270.     calling ShowControl. */
  1271.  
  1272. #pragma segment Main
  1273. void AdjustHV(Boolean isVert, ControlHandle control, TEHandle    docTE, Boolean canRedraw)
  1274. {
  1275.     short        value, lines, max;
  1276.     short        oldValue, oldMax;
  1277.     TEPtr        te;
  1278.     
  1279.     oldValue = GetControlValue(control);
  1280.     oldMax = GetControlMaximum(control);
  1281.     te = *docTE;                            /* point to TERec for convenience */
  1282.     if ( isVert ) {
  1283.         lines = te->nLines;
  1284.         /* since nLines isn’t right if the last character is a return, check for that case */
  1285.         if ( *(*te->hText + te->teLength - 1) == kCrChar )
  1286.             lines += 1;
  1287.         max = lines - ((te->viewRect.bottom - te->viewRect.top) /
  1288.                 te->lineHeight);
  1289.     } else
  1290.         max = kMaxDocWidth - (te->viewRect.right - te->viewRect.left);
  1291.     
  1292.     if ( max < 0 ) max = 0;
  1293.     SetControlMaximum(control, max);
  1294.     
  1295.     /* Must deref. after SetCtlMax since, technically, it could draw and therefore move
  1296.         memory. This is why we don’t just do it once at the beginning. */
  1297.     te = *docTE;
  1298.     if ( isVert )
  1299.         value = (te->viewRect.top - te->destRect.top) / te->lineHeight;
  1300.     else
  1301.         value = te->viewRect.left - te->destRect.left;
  1302.     
  1303.     if ( value < 0 ) value = 0;
  1304.     else if ( value >  max ) value = max;
  1305.     
  1306.     SetControlValue(control, value);
  1307.     /* now redraw the control if it needs to be and can be */
  1308.     if ( canRedraw || (max != oldMax) || (value != oldValue) )
  1309.         ShowControl(control);
  1310. } /*AdjustHV*/
  1311.  
  1312.  
  1313. /* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
  1314.  
  1315. #pragma segment Main
  1316. void AdjustScrollValues(WindowPtr window, Boolean canRedraw)
  1317. {
  1318.     DocumentPeek doc;
  1319.     
  1320.     doc = (DocumentPeek)window;
  1321.     AdjustHV(true, doc->docVScroll, doc->docTE, canRedraw);
  1322.     AdjustHV(false, doc->docHScroll, doc->docTE, canRedraw);
  1323. } /*AdjustScrollValues*/
  1324.  
  1325.  
  1326. /*    Re-calculate the position and size of the viewRect and the scrollbars.
  1327.     kScrollTweek compensates for off-by-one requirements of the scrollbars
  1328.     to have borders coincide with the growbox. */
  1329.  
  1330. #pragma segment Main
  1331. void AdjustScrollSizes(WindowPtr window)
  1332. {
  1333.     Rect        teRect;
  1334.     DocumentPeek doc;
  1335.     
  1336.     doc = (DocumentPeek) window;
  1337.     GetTERect(window, &teRect);                            /* start with TERect */
  1338.     (*doc->docTE)->viewRect = teRect;
  1339.     AdjustViewRect(doc->docTE);                            /* snap to nearest line */
  1340.     MoveControl(doc->docVScroll, window->portRect.right - kScrollbarAdjust, -1);
  1341.     SizeControl(doc->docVScroll, kScrollbarWidth, (window->portRect.bottom - 
  1342.                 window->portRect.top) - (kScrollbarAdjust - kScrollTweek));
  1343.     MoveControl(doc->docHScroll, -1, window->portRect.bottom - kScrollbarAdjust);
  1344.     SizeControl(doc->docHScroll, (window->portRect.right - 
  1345.                 window->portRect.left) - (kScrollbarAdjust - kScrollTweek),
  1346.                 kScrollbarWidth);
  1347. } /*AdjustScrollSizes*/
  1348.  
  1349.  
  1350. /* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
  1351.     and we don't want that). If the controls are to be resized as well, call the procedure to do that,
  1352.     then call the procedure to adjust the maximum and current values. Finally re-enable the controls
  1353.     by jamming a $FF in their contrlVis fields. */
  1354.  
  1355. #pragma segment Main
  1356. void AdjustScrollbars(WindowPtr window, Boolean    needsResize)
  1357. {
  1358.     DocumentPeek doc;
  1359.     
  1360.     doc = (DocumentPeek) window;
  1361.     /* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
  1362.     (*doc->docVScroll)->contrlVis = kControlInvisible;    /* turn them off */
  1363.     (*doc->docHScroll)->contrlVis = kControlInvisible;
  1364.     if ( needsResize )                                    /* move & size as needed */
  1365.         AdjustScrollSizes(window);
  1366.     AdjustScrollValues(window, needsResize);            /* fool with max and current value */
  1367.     /* Now, restore visibility in case we never had to ShowControl during adjustment */
  1368.     (*doc->docVScroll)->contrlVis = kControlVisible;    /* turn them on */
  1369.     (*doc->docHScroll)->contrlVis = kControlVisible;
  1370. } /* AdjustScrollbars */
  1371.  
  1372.  
  1373. /* Gets called from our assembly language routine, AsmClikLoop, which is in
  1374.     turn called by the TEClick toolbox routine. Saves the windows clip region,
  1375.     sets it to the portRect, adjusts the scrollbar values to match the TE scroll
  1376.     amount, then restores the clip region. */
  1377.  
  1378. #pragma segment Main
  1379. pascal  void PascalClikLoop(void)
  1380. {
  1381.     WindowPtr    window;
  1382.     RgnHandle    region;
  1383.     
  1384.     window = FrontWindow();
  1385.     region = NewRgn();
  1386.     GetClip(region);                    /* save clip */
  1387.     ClipRect(&window->portRect);
  1388.     AdjustScrollValues(window, true);    /* pass true for canRedraw */
  1389.     SetClip(region);                    /* restore clip */
  1390.     DisposeRgn(region);
  1391. } /* Pascal/C ClikLoop */
  1392.  
  1393.  
  1394. /* Gets called from our assembly language routine, AsmClikLoop, which is in
  1395.     turn called by the TEClick toolbox routine. It returns the address of the
  1396.     default clikLoop routine that was put into the TERec by TEAutoView to
  1397.     AsmClikLoop so that it can call it. */
  1398.  
  1399. #pragma segment Main
  1400. pascal ProcPtr GetOldClikLoop(void)
  1401. {
  1402.     return ((DocumentPeek)FrontWindow())->docClik;
  1403. } /* GetOldClikLoop */
  1404.  
  1405.  
  1406. /*    Check to see if a window belongs to the application. If the window pointer
  1407.     passed was NIL, then it could not be an application window. WindowKinds
  1408.     that are negative belong to the system and windowKinds less than userKind
  1409.     are reserved by Apple except for windowKinds equal to dialogKind, which
  1410.     mean it is a dialog.
  1411.     1.02 - In order to reduce the chance of accidentally treating some window
  1412.     as an AppWindow that shouldn't be, we'll only return true if the windowkind
  1413.     is userKind. If you add different kinds of windows to Sample you'll need
  1414.     to change how this all works. */
  1415.  
  1416. #pragma segment Main
  1417. Boolean IsAppWindow(WindowPtr window)
  1418. {
  1419.     short        windowKind;
  1420.  
  1421.     if ( window == nil )
  1422.         return false;
  1423.     else {    /* application windows have windowKinds = userKind (8) */
  1424.         windowKind = ((WindowPeek) window)->windowKind;
  1425.         return (windowKind == userKind);
  1426.     }
  1427. } /*IsAppWindow*/
  1428.  
  1429.  
  1430. /* Check to see if a window belongs to a desk accessory. */
  1431.  
  1432. #pragma segment Main
  1433. Boolean IsDAWindow(window)
  1434.     WindowPtr    window;
  1435. {
  1436.     if ( window == nil )
  1437.         return false;
  1438.     else    /* DA windows have negative windowKinds */
  1439.         return ((WindowPeek) window)->windowKind < 0;
  1440. } /*IsDAWindow*/
  1441.  
  1442.  
  1443. /*    Check to see if a given trap is implemented. This is only used by the
  1444.     Initialize routine in this program, so we put it in the Initialize segment.
  1445.     The recommended approach to see if a trap is implemented is to see if
  1446.     the address of the trap routine is the same as the address of the
  1447.     Unimplemented trap. */
  1448. /*    1.02 - Needs to be called after call to SysEnvirons so that it can check
  1449.     if a ToolTrap is out of range of a pre-MacII ROM. */
  1450.  
  1451. #pragma segment Initialize
  1452. Boolean TrapAvailable(short tNumber, TrapType tType)
  1453. {
  1454.     if ( ( tType == (unsigned char) ToolTrap ) &&
  1455.         ( gMac.machineType > envMachUnknown ) &&
  1456.         ( gMac.machineType < envMacII ) ) {        /* it's a 512KE, Plus, or SE */
  1457.         tNumber = tNumber & 0x03FF;
  1458.         if ( tNumber > 0x01FF )                    /* which means the tool traps */
  1459.             tNumber = _Unimplemented;            /* only go to 0x01FF */
  1460.     }
  1461.     return NGetTrapAddress(tNumber, tType) != NGetTrapAddress(_Unimplemented, ToolTrap);
  1462. } /*TrapAvailable*/
  1463.  
  1464.  
  1465. /*    Display an alert that tells the user an error occurred, then exit the program.
  1466.     This routine is used as an ultimate bail-out for serious errors that prohibit
  1467.     the continuation of the application. Errors that do not require the termination
  1468.     of the application should be handled in a different manner. Error checking and
  1469.     reporting has a place even in the simplest application. The error number is used
  1470.     to index an 'STR#' resource so that a relevant message can be displayed. */
  1471.  
  1472. #pragma segment Main
  1473. void AlertUser(short error)
  1474. {
  1475.     short        itemHit;
  1476.     Str255        message;
  1477.  
  1478.     SetCursor(&qd.arrow);
  1479.     /* type Str255 is an array in MPW 3 */
  1480.     GetIndString(message, kErrStrings, error);
  1481.     ParamText(message, (unsigned char *)"", (unsigned char *)"", (unsigned char *)"");
  1482.     itemHit = Alert(rUserAlert, nil);
  1483. } /* AlertUser */
  1484.